/*
 * Copyright 2011 Subhabrata Ghosh <subho.ghosh at langene.net>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



package net.langene.common;

//~--- non-JDK imports --------------------------------------------------------

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//~--- JDK imports ------------------------------------------------------------

import java.util.Date;
import java.util.UUID;

//~--- classes ----------------------------------------------------------------

/**
 *
 * @author Subhabrata Ghosh <subho.ghosh at langene.net>
 *
 * @param <R>
 */
public abstract class Job<R> implements Runnable {
    private static Logger	_logger = LoggerFactory.getLogger(Job.class);

    //~--- fields -------------------------------------------------------------

    /** Field description */
    protected long	endTime;

    /** Field description */
    protected Exception	exception;

    /** Field description */
    protected String	id;

    /** Field description */
    protected Object[]	params;

    /** Field description */
    protected R	returnvalue;

    /** Field description */
    protected long	startTime;

    /** Field description */
    protected JobStatus	status;

    //~--- constructors -------------------------------------------------------

    /**
     * Create a new instance of a Job.
     */
    protected Job() {
        this.id = UUID.randomUUID().toString();
        status  = JobStatus.Initialized;
    }

    //~--- get methods --------------------------------------------------------

    /**
     * @return the Job's Return Value
     */
    public R getReturnvalue() {
        return returnvalue;
    }

    /**
     * @return the endTime
     */
    public long getEndTime() {
        return endTime;
    }

    //~--- set methods --------------------------------------------------------

    /**
     * @param endTime the endTime to set
     */
    public void setEndTime(long endTime) {
        this.endTime = endTime;
    }

    //~--- get methods --------------------------------------------------------

    /**
     * @return the exception
     */
    public Exception getException() {
        return exception;
    }

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @return the params
     */
    public Object[] getParams() {
        return params;
    }

    /**
     * @return the startTime
     */
    public long getStartTime() {
        return startTime;
    }

    //~--- set methods --------------------------------------------------------

    /**
     * @param startTime the startTime to set
     */
    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    //~--- get methods --------------------------------------------------------

    /**
     * @return the status
     */
    public JobStatus getStatus() {
        return status;
    }

    /**
     * Get the Running time for this Job.
     *
     * @return
     */
    public long getRunningTime() {
        if (status == JobStatus.Running) {
            return new Date().getTime() - startTime;
        }

        if ((status == JobStatus.Finished) || (status == JobStatus.Exception)) {
            return endTime - startTime;
        }

        return -1;
    }

    //~--- methods ------------------------------------------------------------

    /**
     * Abstract method, needs to be implemented by sub-classes
     * This method will be invoked when the Job is run.
     *
     * @return
     * @throws Exception
     */
    protected abstract R execute() throws Exception;

    /**
     * Dispose this Job instance.
     *
     * This method should be overridden as appropriate, but subcalsses
     * should always invoke Job.dispose();
     */
    public void dispose() {
        try {
            JobManager.get().remove(this);
        } catch (Exception nex) {
            _logger.error("JOB[" + this.id + "] : ERROR -> " + nex.getLocalizedMessage());
            ProgramUtils.printStacktrace(_logger, nex);
        }
    }

    @Override
    public void run() {
        try {
            status      = JobStatus.Running;
            startTime   = new Date().getTime();
            returnvalue = execute();
            status      = JobStatus.Finished;
        } catch (Exception e) {
            _logger.error("JOB[" + this.id + "] : Exception -> " + e.getLocalizedMessage());
            status    = JobStatus.Exception;
            exception = e;
        } finally {
            try {
                JobManager.get().jobFinished(this);
            } catch (Exception nex) {
                _logger.error("JOB[" + this.id + "] : ERROR -> " + nex.getLocalizedMessage());
                ProgramUtils.printStacktrace(_logger, nex);
            }

            endTime = new Date().getTime();
        }
    }

    /**
     * Force terminate the Job.
     * Note: Might take a while to actually terminate, doesn't raise
     * an interrupt to terminate the thread.
     */
    public void terminate() {
        status    = JobStatus.Terminated;
        exception = new Exception("Job terminated on user request.");
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
